package other.xsy.pms.order;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.*;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.service.XoqlService;
import org.apache.commons.lang.StringUtils;
import other.xsy.pms.utils.ComUtils;
import other.xsy.pms.utils.HCXObjectService;
import other.xsy.pms.utils.PromotionApiUtil;
import other.xsy.pms.utils.TfReturnMsgTools;

import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 订单审核通过后: 把订单信息推送给PMS
 * @Author 黎炎松
 * 2024-06-04 10:05
 */
@RestApi(baseUrl = "/pms")
public class PushOrderToPms implements ApprovalEvent {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "推送CRM订单到PMS ==> ";

    /**
     * 审批触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public ApprovalEventResponse execute(ApprovalEventRequest request) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + "审批流触发开始");
        logger.info("ObjectApiKey:" + request.getEntityApiKey() + " , DataId:" + request.getDataId());
        logger.info(request.toString());
        ApprovalEventResponse response = new ApprovalEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        pushPmsOrderData(request.getDataId());
        return response;
    }

    /**
     * 手动推送订单数据
     * @param id
     * @return
     */
    @RestMapping(value = "/pushPmsOrderData", method = RequestMethod.POST)
    public String doOpt(@RestQueryParam(name = "id") Long id) {
        logger.info(LOGGER_MSG + "执行了按钮事件 = " + id);
        return pushPmsOrderData(id);
    }

    public static void main(String[] args) throws ApiEntityServiceException, ParseException {
        PushOrderToPms pushOrderToPms = new PushOrderToPms();
        pushOrderToPms.pushPmsOrderData(3693779822631569L);
    }


    /**
     * 推送pms订单数据
     * @param orderId
     */
    public String pushPmsOrderData(Long orderId){
        try {
            Order order = new Order();
            order.setId(orderId);
            order = hcxObjectService.get(order);
            Long entityType = order.getEntityType();
            logger.debug(LOGGER_MSG + "处理开始:" + order);

            // 只推送业务类型为 项目订单: 3309750193298054 预交付订单: 3309752318565039
            List<Long> includeTypeList = Arrays.asList(3309750193298054L, 3309752318565039L);
            if (!includeTypeList.contains(entityType)) {
                logger.debug(LOGGER_MSG + "当前订单业务类型无需推送: " + entityType);
                return TfReturnMsgTools.getFailResult("当前订单业务类型无需推送: " + entityType);
            }

            // 获取附件信息
            String sql = "select id,oaApprovalFile__c,contractId.letter_entrusted__c letter_entrusted,contractId.invitation_notice__c invitation_notice," +
                    " contractId.letter_of_acceptance__c letter_of_acceptance,opportunityId.SF_ID__c sfId from _order where id =" + orderId;
            List<JSONObject> fileRecords = XoqlService.instance().query(sql, true).getRecords();

            // 获取税率通用选项集
            JSONArray taxRatePicks = ComUtils.getGlobalPicks("globalPick83__c");

            // 获取订单信息
            JSONObject sendData = new JSONObject();
            sendData.put("orderId", orderId); // 订单id
            sendData.put("orderNo", order.getPo()); // 订单编号
            sendData.put("name", order.getOrderName__c()); // 订单名称
            sendData.put("taxIncludedAmount", ComUtils.dealAmountChange(order.getAmountTZ__c())); // 含税金额 amountTZ__c
            sendData.put("untaxedAmount", ComUtils.dealAmountChange(order.getOrderAmount__c())); // 不含税金额 orderAmount__c
            sendData.put("signDate", order.getOrderSigningDate__c()); // 签订日期 orderSigningDate__c
            sendData.put("effectiveDate", order.getEffectiveDate()); // 生效日期
            sendData.put("filingDate", order.getCustomItem205__c()); // 归档日期
            sendData.put("customerType", order.getType__c()); // 客户类型
            sendData.put("businessType", order.getEntityType()); // 业务类型
            sendData.put("state", order.getOrderStatus__c()); // 状态

            // 业务机会id sfId > crmId
            String sfId = "";
            sendData.put("opportunityId", order.getOpportunityId());

            // 附件赋值
            if (fileRecords.size() > 0) {
                JSONObject orderObj = fileRecords.get(0);
                sfId = orderObj.getString("sfId");
                if (StringUtils.isNotBlank(sfId)) {
                    sendData.put("opportunityId", sfId);
                }

                sendData.put("contractFile", orderObj.getString("oaApprovalFile__c")); // 合同扫描件
                sendData.put("letterEntrusted", orderObj.getString("letter_entrusted")); // 提前入场实施委托函
                sendData.put("invitationNotice", orderObj.getString("invitation_notice")); // 邀请提前入场委托通知
                sendData.put("letterOfAcceptance", orderObj.getString("letter_of_acceptance")); // 中标通知书
            }

            // 获取订单明细
            sql = "select id,productId,priceTotal,contractUntaxedA__c,SF_SL__c,unitPrice,quantity2__c,discount" +
                    " from orderProduct where orderId = " + orderId;
            List<OrderProduct> orderProductList = hcxObjectService.query(sql, OrderProduct.class);

            // 获取产品信息
            String orderProductIds = orderProductList.stream().map(v -> v.getProductId().toString()).collect(Collectors.joining(","));
            sql = "select id,productName,productCode__c from product where id in (" + orderProductIds + ")";
            List<Product> productList = hcxObjectService.query(sql, Product.class);

            JSONArray childData = new JSONArray();
            for (OrderProduct orderProduct : orderProductList) {
                JSONObject jsonObject = new JSONObject();

                jsonObject.put("orderId", orderId); // 订单id
                jsonObject.put("detailId", orderProduct.getId()); // 订单明细id

                Product product = productList.stream().filter(v -> Objects.equals(v.getId(), orderProduct.getProductId())).findFirst().orElse(null);
                if (product != null) {
                    jsonObject.put("productNo", product.getProductCode__c()); // 产品编码
                    jsonObject.put("productName", product.getProductName()); // 产品名称
                }

                jsonObject.put("contractAmountTax", ComUtils.dealAmountChange(orderProduct.getPriceTotal())); // 合同金额 含税
                jsonObject.put("contractAmount", ComUtils.dealAmountChange(orderProduct.getContractUntaxedA__c())); // 合同金额 不含税
                jsonObject.put("taxRate", ComUtils.getOptionLabel(taxRatePicks, orderProduct.getSF_SL__c())); // 税率 (目前传的是 单选 code的值，是否需要调整为label的值)
                jsonObject.put("price", ComUtils.dealAmountChange(orderProduct.getUnitPrice())); // 单价
                jsonObject.put("amount", ComUtils.dealAmountChange(orderProduct.getQuantity2__c())); // 数量 （目前传的是 数量， 实际中还有 周期 字段， 实际数量 = 数量 * 周期）
                jsonObject.put("discount", ComUtils.dealAmountChange(orderProduct.getDiscount())); // 折扣

                childData.add(jsonObject);
            }
            sendData.put("orderProductList", childData);
            logger.debug(LOGGER_MSG + "sendData: " + sendData);

            // 推送数据到 PMS
            JSONObject response = PromotionApiUtil.sendPmsPost(sendData, PromotionApiUtil.INSERT_ORDER_URL);
            Integer code = response.getInteger("code");
            logger.debug(LOGGER_MSG + "code: " + code);

            // 如果 code 为 -2 , 且有 sfId, 则使用业务机会id重新推送
            if (Objects.equals(code, -2) && StringUtils.isNotBlank(sfId)) {
                logger.error(LOGGER_MSG + "重新推送订单数据 = " + order.getOpportunityId());
                sendData.put("opportunityId", order.getOpportunityId());
                response = PromotionApiUtil.sendPmsPost(sendData, PromotionApiUtil.INSERT_ORDER_URL);
                code = response.getInteger("code");
                logger.debug(LOGGER_MSG + "重新推送订单数据 code = " + code);
            }

            if (!Objects.equals(code, 0)) {
                logger.error(LOGGER_MSG + "推送订单数据不成功: " + response.getString("msg"));
                upOrderPmsSyncStatus(order, 2);
                return TfReturnMsgTools.getFailResult("推送订单数据不成功: " + response.getString("msg"));
            }

            // 更新状态
            if (Objects.equals(order.getPushPmsStatus__c(), 2)) {
                upOrderPmsSyncStatus(order, 1);
            }
            logger.info(LOGGER_MSG + "推送成功");
            return TfReturnMsgTools.getSuccessResult("推送成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(LOGGER_MSG + "处理异常:" + e.getMessage());
            return TfReturnMsgTools.getFailResult("推送订单数据异常:" + e.getMessage());
        }
    }

    /**
     * 更新订单同步状态
     * @param order
     */
    public void upOrderPmsSyncStatus(Order order, int status) throws ApiEntityServiceException {
        Order upOrder = new Order();
        upOrder.setId(order.getId());
        upOrder.setPushPmsStatus__c(status);
        hcxObjectService.update(upOrder);
    }

}
